package com.hzz.mall.seckill.interceptor;

import com.atguigu.common.constant.AuthServerConstant;

import com.hzz.mall.seckill.vo.UserInfo1;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfo1> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        // 这个请求直接放行
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match =antPathMatcher.match("/kill", uri);

        if(match){
            // 获取session
            HttpSession session = request.getSession();
            UserInfo1 userInfo1 = new UserInfo1();
            // 获取登录用户
            String username =(String)session.getAttribute(AuthServerConstant.LOGIN_USER);
            Long userId=null;
            if (username!=null){
                userId =Long.valueOf(session.getAttribute(AuthServerConstant.LOGIN_USERId).toString());
            }
            if(username != null){
                userInfo1.setUserName(username);
                userInfo1.setUserId(userId);
                //加上ThreadLocal共享数据，是为了登录后把用户放到本地内存，而不是每次都去远程session里查
                threadLocal.set(userInfo1);
                return true;
            }else{
                // 没登陆就去登录
                session.setAttribute("msg", AuthServerConstant.NOT_LOGIN);
                response.sendRedirect("http://auth.jiajialemall.com/login.html");
                return false;
            }
        }
        return true;

    }
}

